package logic

import (
	"context"
	"encoding/json"
	"shuqi-novel/cache"
	"shuqi-novel/model"
	"shuqi-novel/novelrpc/internal/svc"
	"shuqi-novel/novelrpc/novelrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *novelrpc.ListRequest) (*novelrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	var story []model.Story
	get := cache.Rdb.Get(l.ctx, "NovelList")
	if get.Val() == "" {
		model.DB.Debug().Limit(int(in.Size)).Find(&story)
		marshal, _ := json.Marshal(story)
		cache.Rdb.Set(l.ctx, "NovelList", marshal, time.Minute*30)
	} else {
		json.Unmarshal([]byte(get.Val()), &story)
	}

	var NovelList []*novelrpc.NovelList
	for _, story := range story {
		list := novelrpc.NovelList{
			Img:    story.Img,
			Title:  story.Title,
			About:  story.About,
			Status: story.Status,
		}
		NovelList = append(NovelList, &list)
	}
	return &novelrpc.ListResponse{
		NovelList: nil,
	}, nil
}
